package com.baoyanghui.common;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.Proxy.Type;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;

import org.apache.catalina.util.MD5Encoder;

public class Utils {
	static Integer rewrite = null;
	
	/**
	 * 判断字符串是否为空
	 *
	 * @param	String	str
	 * @return	true: 为空,	false: 不为空
	 */
	public static boolean empty(String str) {
		if (str == null || "".equals(str.trim())) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * 创建像这样的查询: "IN('a','b')";
	 *
	 * @param    List<String>	itemList      列表数组
	 * @param    string   		fieldName     字段名称
	 *
	 * @return   组建完成的条件字符串
	 */
	public static String db_create_in(List<String> itemList, String fieldName)
	{
	    if (itemList == null || itemList.size() == 0)
	    {
	        return fieldName + " IN ('') ";
	    }
	    else
	    {
	        String item_list_tmp = "";
	        for (String item : itemList) {
	            if (!"".equals(item))
	            {
	                item_list_tmp += "".equals(item_list_tmp) ? "'" + item  + "'": ",'" + item + "'";
	            }
	        }
	        return fieldName + " IN (" + item_list_tmp + ") ";

	    }
	}
	
	public static String getDateYMD(long time) {
		String result = "";
		Calendar current = Calendar.getInstance();
		current.setTimeInMillis(time);
		result += current.get(Calendar.YEAR);
		result += String.format("%02d", current.get(Calendar.MONTH) + 1);
		result += String.format("%02d", current.get(Calendar.DATE));
		
		return result;
	}
	
	public static String getDateY_M_D(long time) {
		String result = "";
		Calendar current = Calendar.getInstance();
		current.setTimeInMillis(time);
		result += current.get(Calendar.YEAR);
		result += "-" + String.format("%02d", current.get(Calendar.MONTH) + 1);
		result += "-" + String.format("%02d", current.get(Calendar.DATE));
		
		return result;
	}
	
	/**
	 * 生成字符串的MD5签名
	 *
	 * @param	String msg	原字符串
	 * @return	MD5签名
	 */
	public static String md5(String msg) throws UnsupportedEncodingException, NoSuchAlgorithmException {
		MessageDigest md = null;
		md = MessageDigest.getInstance("MD5");
		return new MD5Encoder().encode(md.digest(msg.getBytes("UTF-8")));
	}
	
	/**
	 * 对 MYSQL LIKE 的内容进行转义
	 *
	 * @param       string      str  内容
	 * @return      string
	 */
	public static String mysqlLikeQuote(String str)
	{
		return str.replaceAll("\\\\", "\\\\\\\\").replaceAll("_", "\\_").replaceAll("%", "\\%").replaceAll("\\'", "\\\\\\'");
	}
	
	/**
	 * 把Java对象转成Json字符串
	 *
	 * @param       Object      Java对象
	 * @return      string
	 */
	public static String genJsonString(Object object) {
		JsonConfig jconfig = new JsonConfig();
		jconfig.setJsonPropertyFilter(new PropertyFilter() {
			
			public boolean apply(Object arg0, String arg1, Object arg2) {
				if (arg2 == null) {return true;}
				if (arg2 instanceof Integer && Integer.parseInt(arg2.toString()) == -1) {return true;}
				if (arg2 instanceof Float && Float.parseFloat(arg2.toString()) == -1) {return true;}
				if (arg2 instanceof Double && Double.parseDouble(arg2.toString()) == -1) {return true;}
				if (arg2 instanceof Long && Long.parseLong(arg2.toString()) == -1) {return true;}
				return false;
			}
		});
		return JSONObject.fromObject(object, jconfig).toString();
	}
	
	/**
	 * 把字符串转成List<String>对象
	 */
	public static List<String> stringToList(String src) {
		List<String> result = new ArrayList<String>();
		
		if (src == null || "".equals(src.trim())) { return result; }
		for( String string : src.split(",")) {
			result.add(string);
        }
		
		return result;
	}
	
	/**
	 * 给参数键名排序
	 */
	public static List<String> sortKeys(Set<String> keys) {
		List<String> keyList = new ArrayList<String>();
		Iterator<String> iterator = keys.iterator();
		while ( iterator.hasNext()) {
			String key = iterator.next();
			keyList.add(key);
		}
		
		Collections.sort(keyList);
		
		return keyList;
	}
	
	/**
	 * 将时间戳转化成字符串日期
	 * @return 日期字符(串格式：HH小时mm分ss秒)
	 */
	public static String getStrTime2(long time) {
		long hour = 0, minute = 0, second = 0;
		
		hour = time / (1000 * 60 * 60);
		minute = (time / (1000 * 60)) % 60;
		second = (time / 1000) % 60;
		
		return hour + "小时" + minute + "分" + second + "秒";
	}
	
	/**
	 * 将时间戳转化成字符串日期
	 * @return 日期字符(串格式：yyyy-MM-dd HH:mm:ss)
	 */
	public static String getStrTime(long time) { 
		String re_StrTime = null; 
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		re_StrTime = sdf.format(new Date(time)); 
		return re_StrTime; 
	}
	
	/**
	 * 将时间戳转化成字符串日期
	 * @return 日期字符(串格式：yyyy-MM-dd HH:mm:ss)
	 */
	public static String getStrTime(String cc_time) { 
		String re_StrTime = null; 
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		long lcc_time = Long.valueOf(cc_time)+28800; 
		re_StrTime = sdf.format(new Date(lcc_time * 1000L)); 
		return re_StrTime; 
	}

	/**
	 * 根据地址获取GPS坐标
	 * @param address	地址
	 * @return GPS坐标
	 */
	public static String getGpsLocation(String address) throws MalformedURLException, IOException {
		String ret = "";
		String gps = "";
		String baseurl = "http://maps.google.com/maps/api/geocode/json?";
		
		try {
			baseurl += "address=" + URLEncoder.encode(address, "UTF-8") + "&sensor=false";
			Proxy proxy = new Proxy(Type.HTTP, InetSocketAddress.createUnresolved("192.168.40.33", 3128));
			URLConnection conn = new URL(baseurl).openConnection(proxy);
			BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
			String line = br.readLine();
			while (line != null) {
				ret += line;
				line = br.readLine();
			}
			
			br.close();
	
			gps = JSONObject.fromObject(ret).getJSONArray("results").getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getString("lat");
			gps += "," + JSONObject.fromObject(ret).getJSONArray("results").getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getString("lng");
			
			return gps;
		} catch (Exception e) {
			return "0,0";
		}
	}
}
